//
//  SettingViewController.m
//  YunGou
//
//  Created by macbook on 16/5/17.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "SettingViewController.h"
#import "LoginViewController.h"
#import "SafeSettingViewController.h"
#import "PersonalInfoViewController.h"
#import "FeedbackViewController.h"
#import "AboutUsViewController.h"
#import "HelpCenterViewController.h"
#import "JPUSHService.h"
#import <UIImageView+WebCache.h>

@interface SettingViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) NSArray *sectionArray;
@property (nonatomic,assign) BOOL isThirdLogin;
@property (nonatomic,strong) UIButton *bottomView;
@property (nonatomic,strong) UITableView *tableView;
@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
}

- (void)changePush:(UISwitch *)isPush{
    if ([isPush isOn]) {
        if (IOS8) {
            //可以添加自定义categories
            [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound |UIUserNotificationTypeAlert) categories:nil];
        } else {
            [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)categories:nil];
        }
        [UserDefaults setObject:@"YES" forKey:@"isPush"];
    }else{
        if (IOS8) {
            [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeNone) categories:nil];
        } else {
            [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeNone) categories:nil];
        }
        [UserDefaults setObject:@"NO" forKey:@"isPush"];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _isThirdLogin = [UserDefaults boolForKey:@"ThirdLogin"];
    if (!IsLogin || (IsLogin && !_isThirdLogin)) {
        _sectionArray = @[@[@"编辑个人资料"],@[@"安全设置"],@[@"推送消息",@"用户反馈",@"帮助中心",@"关于我们",@"清理缓存"]];
    }else{
        _sectionArray = @[@[@"编辑个人资料"],@[@"推送消息",@"用户反馈",@"帮助中心",@"关于我们",@"清理缓存"]];
    }
    if (IsLogin) {
        self.tableView.tableFooterView = self.bottomView;
    }else{
        self.tableView.tableFooterView = nil;
    }
    [self.tableView reloadData];
}

#pragma -mark tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _sectionArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == _sectionArray.count - 1) {
        return 5;
    }return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.textLabel.text = _sectionArray[indexPath.section][indexPath.row];
    if (indexPath.row == 0 && indexPath.section == _sectionArray.count - 1) {
        UISwitch *isPushSwitch = [[UISwitch alloc] init];
        [isPushSwitch addTarget:self action:@selector(changePush:) forControlEvents:UIControlEventTouchUpInside];
        isPushSwitch.on = YES;
        isPushSwitch.onTintColor = ThemeColor;
        cell.accessoryView = isPushSwitch;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else{
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 5.0f;
    }return 15.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == _sectionArray.count - 1) {
        return 20.0f;
    }return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == _sectionArray.count - 1) {
        if (indexPath.row == 1) {
            if (!IsLogin) {
                LoginViewController *loginVC = SB(@"Login", @"LoginVC");
                [self.navigationController pushViewController:loginVC animated:YES];
                return;
            }
            FeedbackViewController *feedbackVC = SB(@"Setting", @"FeedbackVC");
            [self.navigationController pushViewController:feedbackVC animated:YES];
        }else if (indexPath.row == 4){
            unsigned long long size = [SDImageCache sharedImageCache].getSize;
            NSString *sizeText = nil;
            if (size >= pow(10, 9)) { // size >= 1GB
                sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
            } else if (size >= pow(10, 6)) { // 1GB > size >= 1MB
                sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
            } else if (size >= pow(10, 3)) { // 1MB > size >= 1KB
                sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
            } else { // 1KB > size
                sizeText = [NSString stringWithFormat:@"%zdB", size];
            }
            
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"缓存大小%@,确定要清理吗？",sizeText] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertVC addAction:cancelAction];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [MBProgressHUD showMessage:@"正在清除"];
                [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showSuccess:@"清除完毕"];
                }];
            }];
            [alertVC addAction:okAction];
            [self presentViewController:alertVC animated:YES completion:nil];
            
        }else if (indexPath.row == 3){
            AboutUsViewController *aboutUs = [[AboutUsViewController alloc] init];
            [self.navigationController pushViewController:aboutUs animated:YES];
        }else if (indexPath.row == 2){
            HelpCenterViewController *helpVC = [[HelpCenterViewController alloc] init];;
            [self.navigationController pushViewController:helpVC animated:YES];
        }
    }else{
        if (indexPath.section == 0) {
            if (!IsLogin) {
                LoginViewController *loginVC = SB(@"Login", @"LoginVC");
                [self.navigationController pushViewController:loginVC animated:YES];
                return;
            }
            PersonalInfoViewController *personalInfoVC = SB(@"Setting", @"PersonalInfoVC");
            [self.navigationController pushViewController:personalInfoVC animated:YES];
        }else{
            if (!IsLogin) {
                LoginViewController *loginVC = SB(@"Login", @"LoginVC");
                [self.navigationController pushViewController:loginVC animated:YES];
                return;
            }
            SafeSettingViewController *safeSettingVC = SB(@"Setting", @"SafeSettingVC");
            [self.navigationController pushViewController:safeSettingVC animated:YES];
        }
    }
}

- (UIButton *)bottomView{
    if (!_bottomView) {
        _bottomView = [UIButton buttonWithType:UIButtonTypeSystem];
        _bottomView.frame = CGRectMake(0, 0, ScreenWidth, 44);
        [_bottomView setTitleColor:ThemeColor forState:UIControlStateNormal];
        [_bottomView setTitle:@"退出登录" forState:UIControlStateNormal];
        _bottomView.backgroundColor = [UIColor whiteColor];
        [_bottomView addTarget:self action:@selector(loginOut) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomView;
}

- (void)loginOut{
    [UserDefaults setBool:NO forKey:@"is_login"];
    [UserDefaults removeObjectForKey:@"phone"];
    [UserDefaults removeObjectForKey:@"password"];
    [UserDefaults removeObjectForKey:@"uid"];
    [UserDefaults setBool:NO forKey:@"ThirdLogin"];
    
    [[UserModel sharedInstance] clear];
    LoginViewController *loginVC = SB(@"Login", @"LoginVC");
    [self.navigationController pushViewController:loginVC animated:YES];
}

@end
